package controller

import (
	"blog2021/model"
	"blog2021/tools/logger"
	"fmt"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/go-echarts/go-echarts/v2/charts"
	"github.com/go-echarts/go-echarts/v2/opts"
	"github.com/go-echarts/go-echarts/v2/types"
)

func Xaxis() []string {
	var result = make([]string, 0, 24)
	for i := 0; i < 24; i++ {
		result = append(result, strconv.FormatInt(int64(i), 10)+"点")
	}
	return result
}

func SeriesDatas(date string) []opts.LineData {
	lineDatas := []opts.LineData{}
	datas, err := model.HourCount(date)
	if err != nil {
		return lineDatas
	}

	counts := 0
	for _, v := range datas {
		counts += v.Count
		lineDatas = append(lineDatas, opts.LineData{Value: counts})
	}
	return lineDatas
}

func ChartPostAccess(c *gin.Context) {
	datas, err := model.PostAccess()
	if err != nil {
		logger.Error(err)
		ResponseMessage(c, "ERROR", err.Error())
		return
	}

	fmt.Println(datas)
}

func ChartHourCount(c *gin.Context) {
	count := c.Param("count")
	n, err := strconv.ParseInt(count, 10, 32)
	if err != nil || n <= 0 || n >= 15 {
		n = 3
	}

	// create a new line instance
	line := charts.NewLine()
	// set some global options like Title/Legend/ToolTip or anything else
	line.SetGlobalOptions(
		charts.WithInitializationOpts(opts.Initialization{Theme: types.ThemeWesteros}),
		charts.WithTitleOpts(opts.Title{
			Title: "Ningto博客近期访问量曲线",
		}),
		charts.WithLegendOpts(opts.Legend{Show: true, Top: "5%"}),
	)

	line.SetXAxis(Xaxis())

	for i := 0; i < int(n); i++ {
		datestr := time.Now().AddDate(0, 0, -1*i).Format("2006-01-02")
		lineDatas := SeriesDatas(datestr)
		if len(lineDatas) > 0 {
			line.AddSeries(datestr, lineDatas)
		}
	}
	line.SetSeriesOptions(
		charts.WithLineChartOpts(opts.LineChart{Smooth: true}),
	)
	line.Render(c.Writer)
}
